package com.hzvdvmc.autosale.sale;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.hzvdvmc.autosale.MyApp;
import com.hzvdvmc.autosale.R;
import com.hzvdvmc.autosale.base.BaseActivity;
import com.hzvdvmc.autosale.common.OnItemClickListener;
import com.hzvdvmc.autosale.common.TipConstant;
import com.hzvdvmc.autosale.constant.GlobleCache;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.constant.TimeConstant;
import com.hzvdvmc.autosale.sale.adapter.GoodsAdapter;
import com.hzvdvmc.autosale.sale.bean.AdverResBean;
import com.hzvdvmc.autosale.sale.bean.QrCodeResponseBean;
import com.hzvdvmc.autosale.sale.bean.ShopListRespnse;
import com.hzvdvmc.autosale.sale.holder.BannerHolder;
import com.hzvdvmc.autosale.sale.presenter.MainPresenter;
import com.hzvdvmc.autosale.sale.ui.NetStateDialog;
import com.hzvdvmc.autosale.sale.ui.PayDialog;
import com.hzvdvmc.autosale.sale.ui.AdverDialog;
import com.hzvdvmc.autosale.sale.ui.ShopView;
import com.hzvdvmc.autosale.sale.ui.StandByActivity;
import com.hzvdvmc.autosale.seriaport.SerialCallback;
import com.hzvdvmc.autosale.seriaport.SerialClientManager;
import com.hzvdvmc.autosale.seriaport.SerialCmdEnum;
import com.hzvdvmc.autosale.setting.ui.LoginActivity;
import com.hzvdvmc.autosale.socket.SocketClientManager;
import com.hzvdvmc.autosale.socket.event.CommonEvent;
import com.hzvdvmc.autosale.socket.event.TipEvent;
import com.hzvdvmc.autosale.socket.manager.CmdRequestManager;
import com.hzvdvmc.autosale.socket.manager.CmdResponseManager;
import com.hzvdvmc.autosale.util.ActivityUtil;
import com.hzvdvmc.autosale.util.DisplayUtil;
import com.hzvdvmc.autosale.util.FileHelper;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.MachineUtil;
import com.hzvdvmc.autosale.util.NetworkUtils;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static com.hzvdvmc.autosale.constant.TimeConstant.LIVE_DELAY;

/**
 * 首页
 */
public class MainActivity extends BaseActivity implements ShopView {

    @BindView(R.id.videoView)
    VideoView videoView;
    @BindView(R.id.tv_NO)
    TextView tvNO;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.bottom_banner)
    ConvenientBanner bottomBanner;
    @BindView(R.id.btn_setting)
    Button btnSetting;
    @BindView(R.id.btn_all)
    RadioButton btnAll;
    @BindView(R.id.btn_drink)
    RadioButton btnDrink;
    @BindView(R.id.btn_snack)
    RadioButton btnSnack;
    @BindView(R.id.tv_tel)
    TextView tvTel;
    @BindView(R.id.layout_setting)
    RelativeLayout layoutSetting;
    @BindView(R.id.top_banner)
    ConvenientBanner topBanner;
    @BindView(R.id.bottom_videoView)
    VideoView bottomVideoView;

    @BindView(R.id.tv_tip)
    TextView tvTip;
    private static final String TAG = "MainActivity";
    private static final int SPAN_COUNT = 4;

    private GoodsAdapter mAdapter;
    private List<ShopListRespnse.RetObjBean> dataList = new ArrayList<>();

    private List<String> adverBannerImages = new ArrayList<>();
    private List<String> bottomBannerImages = new ArrayList<>();
    private List<String> topBannerImages = new ArrayList<>();
    private int pageSize = 100;
    private int pageIndex = 1;
    private boolean isNeedRefresh;

    private SocketClientManager clientManager;
    private Timer timer;
    private PayDialog payInfoDialog;
    //出货成功后，广告的弹框
    private AdverDialog adverDialog;
    private MainPresenter presenter;
    private TimerTask standByTask;
    private NetStateDialog netStateDialog;

    private List<AdverResBean.RetObjBean> adverTopList = new ArrayList<>();
    private List<AdverResBean.RetObjBean> adverBottomList = new ArrayList<>();
    private List<AdverResBean.RetObjBean> adverOutList = new ArrayList<>();
    private List<AdverResBean.RetObjBean> adverWaitList = new ArrayList<>();
    private int outVideoResPosition;
    private boolean isOutVideoRes;
    private boolean isBottomVideoRes;
    private int bottomVideoResPosition;
    private int topVideoResPosition;

    private boolean isLocalRes = true;

    @OnClick(R.id.btn_setting)
    public void startSetting() {
        startActivity(new Intent(this, LoginActivity.class));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTipEvent(TipEvent event) {
        try {
            tvTip.setVisibility(View.VISIBLE);
            tvTip.setText(event.getContent());
            ToastUtils.showShort(event.getContent());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReceived(CommonEvent event) {
        switch (event.getValue()) {
            case CommonEvent.SIGN_SUCCESS:
                tvTip.setText("签到成功 ");
                disNetStateDialog();
                refreshData();
                resetStandByTask();
                break;
            case CommonEvent.PAY_VERI_SUCCESS:
                ToastUtils.showLong("支付验证成功，正在出货...");
                if (payInfoDialog != null && payInfoDialog.isShowing()) {
                    payInfoDialog.updateState("支付验证成功，正在出货,请稍等...");
                    payInfoDialog.dismiss();
                }

                showVideoTipDialog(TipConstant.out_ing);
                break;

            case CommonEvent.PAY_VERI_FAILURE:
                if (payInfoDialog != null && payInfoDialog.isShowing()) {
                    payInfoDialog.updateState("支付验证失败！");
                    payInfoDialog.dismiss();
                }
                break;
            case CommonEvent.PAY_SUCCESS:
                if (payInfoDialog != null && payInfoDialog.isShowing()) {
                    payInfoDialog.updateState("支付成功，正在验证...");
                }
                break;
            case CommonEvent.ONE_KEY_SUPP:
            case CommonEvent.REFRESH_LIST:
                if (ActivityUtil.isForeground(this, getClass().getName())) {
                    //在前台，刷新数据
                    refreshData();
                } else {
                    isNeedRefresh = true;
                }
                break;
            case CommonEvent.OUT_SUCCESS:
                showVideoTipDialog(TipConstant.out_success);
                break;
            case CommonEvent.OUT_FALIURE:
                showVideoTipDialog(TipConstant.out_fail);
                break;
            case CommonEvent.SERIL_OUT_TIME:
                showVideoTipDialog(TipConstant.out_time);
                break;
            case CommonEvent.OPEN_SETTING_LOGIN:
                startActivity(new Intent(this, LoginActivity.class));
                break;
            case CommonEvent.NET_DISCONNET:
                GlobleCache.isSign = false;
                showNetStateDialog("网络连接失败");
                break;
            case CommonEvent.NET_RECONNET:
            case CommonEvent.SOCKET_RECONNET:
                startApplySign();
                break;

            case CommonEvent.SOCKET_DISCONNET:
                showNetStateDialog("服务器已断开");
                GlobleCache.isSign = false;
                break;
            case CommonEvent.REFRESH_ADVERTISEMENT:
                //刷新广告
                refreshAdver();
                break;
        }

        startTipTask();
    }

    private void refreshAdver() {

    }

    public void getDisplayInfo() {
        if (!NetworkUtils.isConnected()) {
            tvTip.setText("网络未连接");
        }
    }

    private void showNetStateDialog(String text) {

        if (isFinishing()){
            return;
        }

        disPayDialog();

        disAdverDialog();

        if (netStateDialog == null) {
            netStateDialog = new NetStateDialog(this, R.style.MyDialog);
        }

        if (!netStateDialog.isShowing()) {
            netStateDialog.show();
        }
        netStateDialog.setText(text);
    }

    private void disNetStateDialog() {
        if (netStateDialog != null && netStateDialog.isShowing()) {
            netStateDialog.dismiss();
        }
    }


    /**
     * 出货间隙，播放广告视频
     */
    private void showVideoTipDialog(String msg) {
        if (adverDialog == null) {
            adverDialog = new AdverDialog(this);
        }

        if (isLocalRes) {
            String adverOutPath = FileHelper.getAdverOutPath();
            if (TextUtils.isEmpty(adverOutPath)){
                return;
            }
            File file = new File(adverOutPath);
            if (file.exists())
                adverDialog.showWithVideo(adverOutPath);
        } else {
            if (isOutVideoRes) {
                //视频
                adverDialog.showWithVideo(adverOutList
                        .get(outVideoResPosition).getSourceUrl());
            } else {
                //轮播图
                adverDialog.showWithBanner(adverBannerImages);
            }
        }

        if (adverDialog.isShowing()) {
            adverDialog.setTvState(msg);
            return;
        }
        adverDialog.setCancelable(false);
        adverDialog.setTvState(msg);

    }

    private void disAdverDialog() {
        if (adverDialog != null && adverDialog.isShowing()) {
            adverDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        timer = new Timer();
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);

        keepLive();

        getDisplayInfo();
        changeLayout();

        initColdSet();

        //加载广告数据
        initAdverData();

        getCurrentNetDBM(this);

        initSaleData();
    }

    private void initAdverData() {
        if (isLocalRes) {

        } else {
            presenter.getAdverRes(MachineUtil.getDeviceNO());
        }
    }

    private void initColdSet() {
        String data = SPUtils.getInstance().getString(SpKey.TEMPUTURE_SET);
        if (!TextUtils.isEmpty(data)) {
            sendSerialData(data);
        }
    }

    private void changeLayout() {
        if (DisplayUtil.isSmallScreen(this)) {
            videoView.setVisibility(View.GONE);
            bottomBanner.setVisibility(View.GONE);

        } else {

            videoView.setVisibility(View.VISIBLE);
            bottomBanner.setVisibility(View.VISIBLE);

            if (isLocalRes) {
                initVideoView(FileHelper.getAdverTopPath());

                initLocalBannerData();

                initBottomBanenr(bottomBannerImages);
            }
        }
    }

    /**
     * 10s后自动隐藏tip
     */
    private void startTipTask() {
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 需要做的事:发送消息
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTip.setText("");
                    }
                });
            }
        };
        timer.schedule(task, 10 * 1000);
    }

    /**
     * 不断申请签到的操作
     */
    private void startApplySign() {
        if (GlobleCache.isSign) {
            disNetStateDialog();
            return;
        }
        showNetStateDialog("正在签到...");
        CmdRequestManager.getInstance().applySignRequest();
    }

    /**
     * 保活
     */
    private void keepLive() {
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 需要做的事:发送消息
                CmdRequestManager.getInstance().keepLiveRequest();
            }
        };
        timer.schedule(task, LIVE_DELAY, LIVE_DELAY);
    }


    private void initSaleData() {
        tvNO.setText("编号：" + MachineUtil.getDeviceNO());
        initRecyclerView();
        clientManager = SocketClientManager.getInstance();
        clientManager.connect();

        loadData();
    }

    private void sendSerialData(String data) {
        SerialClientManager manager = new SerialClientManager();
        manager.setData(data);
        manager.setCallback(SerialCmdEnum.SYSYTEM_PARAMS_MODIFY, new SerialCallback() {
            @Override
            public void onSuccess(String cmd, String data,String tuneNO, String orderNO) {
                String result = data.substring(2, 3);
                if ("0".equals(result)) {
                    LogUtil.p("压缩机设置成功");
                    ToastUtils.showShort("设置成功");
                } else {
                    ToastUtils.showShort("设置失败");
                }
            }

            @Override
            public void onFile(String msg,String tuneNO, String orderNO) {
                ToastUtils.showShort(msg);
            }
        });
        manager.execute();
    }

    private void loadData() {

        presenter = new MainPresenter(this, this);
        getShopList(MachineUtil.getDeviceNO(), pageSize + "", pageIndex + "");
    }

    /**
     * 测试更多的数据
     */
    private void testData() {
        for (int i = 0; i < 50; i++) {
            ShopListRespnse.RetObjBean objBean = new ShopListRespnse.RetObjBean();
            objBean.setAPrice(i + "");
            objBean.setCurrStock("2");
            dataList.add(objBean);
        }
    }

    private void initRecyclerView() {
        mAdapter = new GoodsAdapter(dataList);
        recyclerView.setAdapter(mAdapter);
        GridLayoutManager layoutManager = new GridLayoutManager(this, SPAN_COUNT,
                LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View v, int position) {
                if (CmdResponseManager.getInstance().isSaleOuting()){
                    //正在出货中
                    ToastUtils.showLong("系统忙，请稍候再试...");
                    return;
                }
                if ("0".equals(dataList.get(position).getCurrStock())) {
                    //无货
                    ToastUtils.showShort("该商品已售空");
                    return;
                }
                showPayDialog(position);
                loadCodeValue(dataList.get(position).getWaresId());

            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!recyclerView.canScrollHorizontally(1) && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //水平方向上不能滚动,说明到底了
                    pageIndex++;
                    loadData();
                    //下面是测试的假数据
//                    dataList.addAll(dataList);
//                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    public void loadCodeValue(String waresId) {
        if (presenter != null) {
            presenter.getCodeValue(MachineUtil.getDeviceNO(), waresId);
        }
    }

    public void loadAdver(String machineId) {
        if (presenter != null) {
            String deviceNO = MachineUtil.getDeviceNO();
            presenter.getAdverRes(deviceNO);
        }
    }

    private void showPayDialog(int position) {
        String waresId = dataList.get(position).getWaresId();
        String tunnelId = dataList.get(position).getTunnelId();
        String wPrice = dataList.get(position).getWPrice();
        if (payInfoDialog!=null && payInfoDialog.isShowing()){
            return;
        }
        payInfoDialog = new PayDialog(this);
        payInfoDialog.show();
        payInfoDialog.setData(dataList.get(position));

    }

    private void disPayDialog() {
        if (payInfoDialog != null && payInfoDialog.isShowing()) {
            payInfoDialog.dismiss();
        }
    }

    private void initBottomBanenr(List<String> localImages) {
        bottomVideoView.setVisibility(View.GONE);
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        bottomBanner.setPages(new CBViewHolderCreator<BannerHolder>() {
            @Override
            public BannerHolder createHolder() {
                return new BannerHolder();
            }
        }, localImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setScrollDuration(800);

        bottomBanner.setCanLoop(true);
        //设置翻页的效果，不需要翻页效果可用不设
        //.setPageTransformer(Transformer.DefaultTransformer);    集成特效之后会有白屏现象，新版已经分离，如果要集成特效的例子可以看Demo的点击响应。
        bottomBanner.setManualPageable(false);//设置不能手动影响
        bottomBanner.startTurning(5000);

    }

    private void initTopBanenr(List<String> localImages) {
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        topBanner.setPages(new CBViewHolderCreator<BannerHolder>() {
            @Override
            public BannerHolder createHolder() {
                return new BannerHolder();
            }
        }, localImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setScrollDuration(800);

        topBanner.setCanLoop(true);
        //设置翻页的效果，不需要翻页效果可用不设
        //.setPageTransformer(Transformer.DefaultTransformer);    集成特效之后会有白屏现象，新版已经分离，如果要集成特效的例子可以看Demo的点击响应。
        topBanner.setManualPageable(false);//设置不能手动影响
        topBanner.startTurning(5000);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (clientManager != null) {
            clientManager.disConnect();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    private void initVideoView(final String videoPath) {
        topBanner.setVisibility(View.GONE);
        LogUtil.i(TAG, "video videoPath:" + videoPath);
        if (new File(videoPath).exists()) {
            videoView.setVideoURI(Uri.parse(videoPath));
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(true);
                }
            });
            videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mPlayer) {
                    // TODO Auto-generated method stub
                    videoView.setVideoURI(Uri.parse(videoPath));
                    videoView.start();
                }
            });
            videoView.start();
            videoView.requestFocus();
        } else {
            Toast.makeText(this, "视频文件不存在", Toast.LENGTH_SHORT).show();
            videoView.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoView != null &&
                !videoView.isPlaying()) {
            videoView.start();
        }

        if (isNeedRefresh) {
            isNeedRefresh = false;
            refreshData();
        }

        startApplySign();

        resetStandByTask();

        if (!MyApp.isHeart) {
            try {
                MyApp.startSerialHeart();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        String tel = SPUtils.getInstance().getString(SpKey.TEL);
        if (!TextUtils.isEmpty(tel)) {
            tvTel.setText("电话:"+tel);
        }

    }


    @Override
    protected void onStop() {
        super.onStop();
        if (videoView != null &&
                videoView.isPlaying()) {
            videoView.pause();
        }
        stopStandByTask();
    }

    private void refreshData() {
        dataList.clear();
        pageIndex = 1;
        loadData();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        resetStandByTask();
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 重置屏保任务
     */
    private void resetStandByTask() {

        String ts = SPUtils.getInstance().getString(SpKey.TIME_WAIT);
        int sbTime = Integer.parseInt(ts);

        if (DisplayUtil.isSmallScreen(this)) {
            if (standByTask != null) {
                standByTask.cancel();
            }
            standByTask = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showStandByActivity();
                        }
                    });
                }
            };
            timer.schedule(standByTask, TimeConstant.minute * sbTime);
        }
    }

    /**
     * 停止屏保任务
     */
    private void stopStandByTask() {
        if (standByTask != null) {
            standByTask.cancel();
        }
    }


    private void showStandByActivity() {
        if (GlobleCache.isSign && NetworkUtils.isConnected()) {
            startActivity(new Intent(this, StandByActivity.class));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void getShopList(String machineKey, String pageSize, String pageIndex) {
        if (presenter != null) {
            presenter.getShopList(machineKey, pageSize, pageIndex);
        }
    }

    @Override
    public void onGetShopListSuccess(List<ShopListRespnse.RetObjBean> list) {
        if (list==null ){
            return;
        }
        if (list.isEmpty()){
            return;
        }
        if (pageIndex == 0) {
            dataList.clear();
        }
        dataList.addAll(list);
        if (dataList.isEmpty()){
            ToastUtils.showLong("当前设备暂无商品");
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onGetShopListFailure(String errorMsg) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onGetQrCodeSuccess(final QrCodeResponseBean bean) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (payInfoDialog != null &&
                        payInfoDialog.isShowing() &&
                        payInfoDialog.getWaresId().equals(bean.getWaresId())) {

                    payInfoDialog.setCode(URLDecoder.decode(bean.getUrl()));
                }
            }
        });

    }

    @Override
    public void onGetQrCodeFailure(String errorMsg) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onGetAdverSuccess(AdverResBean bean) {
        clearAdverDataList();
        List<AdverResBean.RetObjBean> retObjList = bean.getRetObj();
        for (int i = 0; i < retObjList.size(); i++) {
            if ("1".equals(retObjList.get(i).getAdType())) {
                adverTopList.add(retObjList.get(i));
                initAdverTop();
            } else if ("2".equals(retObjList.get(i).getAdType())) {
                adverOutList.add(retObjList.get(i));
                initAdverOut();
            } else if ("3".equals(retObjList.get(i).getAdType())) {
                adverBottomList.add(retObjList.get(i));
                initAdverBottom();
            }
        }

    }

    private void initAdverBottom() {
        adverBottomList.clear();
        isBottomVideoRes = false;
        bottomVideoResPosition = 0;

        bottomBannerImages.clear();
        for (int i = 0; i < adverBottomList.size(); i++) {
            String sourceUrl3 = adverBottomList.get(i).getSourceUrl();
            if (isVideo(sourceUrl3)) {
                bottomVideoResPosition = i;
                isBottomVideoRes = true;
            } else {
                bottomBannerImages.add(sourceUrl3);
            }
        }

        if (isBottomVideoRes) {
            bottomVideoView.setVisibility(View.VISIBLE);
            bottomBanner.setVisibility(View.GONE);
            initVideoView(adverBottomList.get(bottomVideoResPosition).getSourceUrl());
        } else {
            bottomVideoView.setVisibility(View.GONE);
            bottomBanner.setVisibility(View.VISIBLE);
            initBottomBanenr(bottomBannerImages);
        }
    }

    private void initAdverOut() {
        isOutVideoRes = false;
        outVideoResPosition = 0;

        adverBannerImages.clear();
        for (int i = 0; i < adverOutList.size(); i++) {
            String sourceUrl2 = adverOutList.get(i).getSourceUrl();
            if (isVideo(sourceUrl2)) {
                outVideoResPosition = i;
                isOutVideoRes = true;
            } else {
                adverBannerImages.add(sourceUrl2);
            }
        }
    }

    private void initAdverTop() {


        boolean isTopVideoRes = false;
        topVideoResPosition = 0;

        topBannerImages.clear();
        for (int i = 0; i < adverTopList.size(); i++) {
            String sourceUrl1 = adverTopList.get(i).getSourceUrl();
            if (isVideo(adverTopList.get(i).getSourceUrl())) {
                topVideoResPosition = i;
                isTopVideoRes = true;
            } else {
                topBannerImages.add(sourceUrl1);
            }
        }

        if (isTopVideoRes) {
            videoView.setVisibility(View.VISIBLE);
            topBanner.setVisibility(View.GONE);
            initVideoView(adverTopList.get(topVideoResPosition).getSourceUrl());
        } else {
            videoView.setVisibility(View.GONE);
            topBanner.setVisibility(View.VISIBLE);
            initTopBanenr(topBannerImages);
        }
    }

    private void clearAdverDataList() {
        adverTopList.clear();
        adverOutList.clear();
        adverBottomList.clear();
    }

    @Override
    public void onGetAdverFailure(String errorMag) {

    }

    /**
     * 判断文件是否是视频
     *
     * @param name 文件名字
     * @return
     */
    private boolean isVideo(String name) {
        if (TextUtils.isEmpty(name)) {
            return false;
        }

        if (name.contains(".mp4") || name.contains(".avi")
                || name.equals(".mkv") || name.equals(".wmv")
                || name.equals(".rm") || name.equals(".rmvb")
                || name.equals(".mpg") || name.equals(".3gb")) {
            return true;
        }

        return false;
    }

    public void getCurrentNetDBM(Context context) {
        final TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        PhoneStateListener mylistener = new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                String signalInfo = signalStrength.toString();
                String[] params = signalInfo.split(" ");
                if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
                    //4G网络 最佳范围   >-90dBm 越大越好
                    int iteDbm = Integer.parseInt(params[9]);
                    iteDbm = iteDbm + 96;
                    if (iteDbm < 0) {
                        iteDbm = 0;
                    }
                    MachineUtil.setNetStrength(iteDbm / (96 / 32));

                } else if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA ||
                        tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPA ||
                        tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSUPA ||
                        tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS) {
                    //3G网络最佳范围  >-90dBm  越大越好  ps:中国移动3G获取不到  返回的无效dbm值是正数（85dbm）
                    //在这个范围的已经确定是3G，但不同运营商的3G有不同的获取方法，故在此需做判断 判断运营商与网络类型的工具类在最下方
                } else {
                    //2G网络最佳范围>-90dBm 越大越好
                    int asu = signalStrength.getGsmSignalStrength();
                    int dbm = -113 + 2 * asu;
                }
            }
        };
        //开始监听
        tm.listen(mylistener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }


    private void initLocalBannerData() {
        bottomBannerImages.clear();
        bottomBannerImages.addAll(FileHelper.getAdverBottomUrlList());
    }
}
